來架個網站吧 GrailsService/dict資料夾中按下右鍵。Grails Domain Class。
在 Service 的文件中主要是處理資料流程,一般API並不會直接觸及Service。在這邊我比較請向處理單一 Domain Class 的資料處理,也就是說有一張 Domain 就會對一個 Service。
Service 通常會有事物流程 @Transactional,在執行 新增、修改、刪除 時還蠻常用到。
而在程式中 GrailsParameterMap ,是前端表單傳入的數值,繼承自 java.util.Map,回傳的資料如下:
[searchWord:一, controller:dict, action:filter]
查詢的方式,這邊我是用 createCriteria 來操作查詢。完成執行查詢之後,將資料轉成 bootstrap table 所需要的資料格式,如下:
{
  "total": 1,
  "rows": [
    {
      "id": 1,
      "word": "一",
      "radical": "一",
      "totalStrokes": 1,
      "outStrokes": 0,
      "mpc": "一",
      "explanation": "...."
    }
  ]
}
package dict
import grails.gorm.transactions.Transactional
import grails.web.servlet.mvc.GrailsParameterMap
@Transactional //事物
class DictService {
  LinkedHashMap filter(GrailsParameterMap params) {
    LinkedHashMap result = [:]
    String word = params?.searchWord
    def dictL = Dict.createCriteria().list(params){
      if(word){
          eq("word",word)
      }
    }
    //將資料轉成 `bootstrap table` 所需要的資料格式
    result.total = dictL.totalCount
    result.rows = dictL.collect { it ->
      [
        id          : it?.id,
        word        : it?.word,
        radical     : it?.radical,
        totalStrokes: it?.totalStrokes,
        outStrokes  : it?.outStrokes,
        mpc         : it?.mpc,
        explanation : it?.explanation,
      ]
    }
    return result
  }
}